package cn.wellcare.portal.controller.demo;

import cn.wellcare.api.acc.IPscPiAccService;
import cn.wellcare.api.trade.IPscAccPaymentService;
import cn.wellcare.core.constant.BaseParam;
import cn.wellcare.core.constant.Constants;
import cn.wellcare.core.constant.PaymentType;
import cn.wellcare.core.exception.BusinessException;
import cn.wellcare.core.exception.ErrorEnum;
import cn.wellcare.core.exception.UnauthorizedException;
import cn.wellcare.core.utils.CommonUtils;
import cn.wellcare.core.utils.Md5SignUtil;
import cn.wellcare.entity.order.PayOrder;
import cn.wellcare.payment.api.PaymentApi;
import cn.wellcare.payment.modules.system.ISysOrganizationService;
import cn.wellcare.payment.order.IOrderService;
import cn.wellcare.pojo.account.PscPiAcc;
import cn.wellcare.pojo.common.AccPaymentResult;
import cn.wellcare.pojo.common.PaymentResult;
import cn.wellcare.pojo.common.RpcResult;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 账户充值演示
 * 
 * @author zhaihl
 *
 */
@RequestMapping("demo/accPay")
@Controller
public class DemoAccPaymentController {
	private Logger log = Logger.getLogger(this.getClass());

	@Resource
	private ISysOrganizationService sysOrganizationService;

	@Resource(name = "accRechargeService")
	private PaymentApi accRechargeService;

	@Resource(name = "pscAccPaymentService")
	private IPscAccPaymentService accountPayService;

	@Resource(name = "pscPiAccService")
	private IPscPiAccService pscPiAccService;

	@Resource(name = "orderService")
	private IOrderService orderService;

	@RequestMapping(value = Constants.DOPAY, produces = Constants.CONTENT_TYPE_JSON)
	@ResponseBody
	public RpcResult<PaymentResult> demopay(HttpServletRequest request, HttpServletResponse response,
			@RequestParam Map<String, Object> param) {
		RpcResult<PaymentResult> result = new RpcResult<>();
		try {
			Assert.notNull(param.get(BaseParam.PAY_TYPE));
			Assert.notNull(param.get(BaseParam.PAY_AMOUNT));
			Assert.notNull(param.get(BaseParam.CLIENT_TRADE_TIME));

			// 1.排序签名
			param.put(BaseParam.CLIENT_IP, CommonUtils.getRemoteIpAddr(request));
			// param.put(BaseParam.BACK_URL, DomainUrlUtil.PSC_PAYMENT_URL +
			// "/demo/serverNotify");

			Map<String, Object> sorted = CommonUtils.sort(param);
			this.log.debug("客户端排序后参数集：" + sorted);

			String securtkey = sysOrganizationService
					.getSysOrganizationById(Integer.valueOf((String) param.get(BaseParam.ORG_ID)))
					.getData().getAuthSecret();
			log.debug("机构密钥：" + securtkey);
			String sign = Md5SignUtil.sginMD5(sorted, securtkey);
			param.put("sign", sign);


			// 2.账户状态
			RpcResult<cn.wellcare.acc.entity.PscPiAcc> sr = pscPiAccService
					.getPscPiAccBypkPi((String) param.get(BaseParam.USER_ID));
			if (CommonUtils.isNull(sr.getData())) {
				throw new BusinessException("找不到账户");
			}
			cn.wellcare.acc.entity.PscPiAcc acc = sr.getData();
			if (PscPiAcc.ACC_ENABLE != Integer.valueOf(acc.getEuStatus())) {
				throw new BusinessException("账户不可用");
			}

			// 3.交易收款
			String payType = PaymentType.getPaymentCodeByNameOrCode((String) param.get(BaseParam.RECHARGE_TYPE));
			Integer orderId = 1;
			if (PaymentType.MISPOS.getPaymentCode().equals(payType)
					|| PaymentType.MISPOS.getPaymentName().equals(payType)) {
				// 订单是否存在
				String ordersn = (String) param.get(BaseParam.ORDER_ID);
				RpcResult<PayOrder> orderresult = orderService.getOrderByOuterSn(ordersn);
				if (!orderresult.isSuccess() || orderresult.getData() == null) {
					throw new BusinessException(ErrorEnum.ORDER_NOT_EXISTS_EXCEPTION.getErrDesc());
				}
				orderId = orderresult.getData().getId();
			} else {
				// 收款
				result = accRechargeService.doPay(param);
				orderId = result.getData().getOrderId();
			}

			if (!result.isSuccess()) {
				// TODO 退款
				throw new BusinessException(Constants.RECHARGE_FAIL);
			}

			param.put(BaseParam.USER_ID, acc.getPkPiacc());
			param.put(BaseParam.ORDER_ID, orderId);

			// 4.账户充值
			RpcResult<AccPaymentResult> accres = accountPayService.accRecharge(param);
			if (!accres.isSuccess()) {
				// TODO 退款
				throw new BusinessException(Constants.RECHARGE_FAIL);
			}
		} catch (Exception e) {
			result.setSuccess(false);
			if (e instanceof BusinessException) {
				BusinessException pe = (BusinessException) e;
				if (pe.getCode() != null && ErrorEnum.BUSINESS_EXCEPTION.getErrCode().equals(pe.getCode()))
					result.setMsgInfo(ErrorEnum.BUSINESS_EXCEPTION.getErrDesc());
				else
					result.setMsgInfo(e.getMessage());
				result.setMsgCode(ErrorEnum.BUSINESS_EXCEPTION.getErrCode());
			} else {
				if (e instanceof UnauthorizedException) {
					result.setError(ErrorEnum.UNAUTHORIZED_EXCEPTION);
				} else {
					e.printStackTrace();
					result.setMsgInfo(ErrorEnum.SERVER_EXCEPTION.getErrDesc());
				}
			}
		}
		return result;
	}



}
